package com.iwhalecloud.bss.kite.cucc.common.mq.serializer;

import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * FSTSerializer
 *
 * @author Linjj
 */
public class FSTSerializer implements Serializer {

    public final Logger logger = LoggerFactory.getLogger(this.getClass());

    public final static FSTConfiguration CONFIG = FSTConfiguration.createDefaultConfiguration();

    @Override
    public byte[] serialize(Object obj) {
        byte[] data = null;
        if (obj == null) {
            return data;
        }
        OutputStream stream = new ByteArrayOutputStream();
        FSTObjectOutput out = CONFIG.getObjectOutput(stream);
        try {
            out.writeObject(obj);
            data = out.getCopyOfWrittenBuffer();
        } catch (Exception e) {
            logger.debug(e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    stream.close();
                } catch (IOException e) {
                }
            }
        }
        return data;
    }


    @Override
    public Object deserialize(byte[] bytes) {
        Object obj = null;
        if (null == bytes || bytes.length == 0) {
            return null;
        }

        InputStream stream = new ByteArrayInputStream(bytes);
        FSTObjectInput in = CONFIG.getObjectInput(stream);
        try {
            obj = in.readObject();
        } catch (Exception e) {
            logger.error("FST Deserialize Failed!", e);
        } finally {
            if (in != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                }
            }
        }

        return obj;
    }

}
